<?

global $_APP_SESSION_THEME;

require_once ("class.fieldset.inc");
require_once ("{$_APP_SESSION_THEME}/template.fieldset.inc");

function _app_process_fieldset ($options) {

	$fieldset = $options["fieldset"];
	$fs_action = $options["fs_action"] ? $options["fs_action"] : "view";
	$fs_action_field = $options["fs_action_field"] ?
			$options["fs_action_field"] : "fs_action";
	$fs_options = $options["fs_options"];
	$fs_primary_key = $options["fs_primary_key"] ?
			$options["fs_primary_key"] : null;
	$fs_trans_begin = $options["fs_trans_begin"];
	$fs_trans_commit = $options["fs_trans_commit"];
	$fs_validate_only = $options["fs_validate_only"];
	
	$input = false;
	$success = false;
	$valid = false;
	$store = false;

	global $_GLOBAL_DBH;

	if ($fs_trans_begin) $_GLOBAL_DBH->query ("BEGIN");

	if ($fs_action == "create") {

		$store = true;

		if ($fieldset->validate ()) {

			if ($fs_validate_only || !$fieldset->store ()) {

				$input = true;
				$fs_action = "addnew";
				$fieldset->parse ("addnew");
			} else {

				$success = true;
				$fs_action = "view";
				$fieldset->parse ("view");
				$fieldset->retrieve ();
				$_REQUEST[$fs_primary_key] =
						$fieldset->get_field
						($fieldset->get_option
						("primary_key"))->
						get_variable ("value");
			}

			$valid = true;
		} else {

			$input = true;
			$fs_action = "addnew";
			$fieldset->parse ("addnew");
		}
	} else if ($fs_action == "update") {

		$store = true;

		if ($fieldset->validate ()) {

			if ($fs_validate_only || !$fieldset->update ()) {

				$input = true;
				$fs_action = "modify";
				$fieldset->parse ("modify");
			} else {

				$success = true;
				$fs_action = "view";
				$fieldset->retrieve ();
				$fieldset->parse ("view");
				$_REQUEST[$fs_primary_key] =
						$fieldset->get_field
						($fieldset->get_option
						("primary_key"))->
						get_variable ("value");
			}

			$valid = true;
		} else {

			$input = true;
			$fs_action = "modify";
			$fieldset->parse ("modify");
		}
	} else if ($fs_action == "remove") {

		$fieldset->parse ("remove");
		$fieldset->retrieve ();
		$_REQUEST[$fs_primary_key] =
				$fieldset->get_field ($fieldset->get_option
				("primary_key"))->get_variable ("value");
	} else if ($fs_action == "delete") {

		if (!$fieldset->remove ()) {

			$fieldset->parse ("view");
			$fieldset->retrieve ();
			$fs_action = "view";
		} else {


			$success = true;
			if (!$fs_trans_commit && !isset ($fs_options[$fs_action]["redirect"]))
					return (array ($input, $fs_action, $store, $valid, $success));

			if (isset ($fs_options[$fs_action]["action"])) {

				if ($fs_trans_commit) {
					$_GLOBAL_DBH->query ("COMMIT");
				}
				require_once ($fs_options[$fs_action]["action"]);
				exit (1);

			} elseif (isset ($fs_options[$fs_action]["redirect"])) {

				if ($fs_trans_commit) {
					$_GLOBAL_DBH->query ("COMMIT");
				}
				header ("Location: {$fs_options[$fs_action]["redirect"]}");
				exit (1);
			}
		}
	} else if ($fs_action == "modify") {

		$fieldset->parse ("modify");
		$fieldset->retrieve (false);
		$input = true;
	} else if ($fs_action == "canret" || $fs_action == "close") {

		if (isset ($fs_options[$fs_action]["action"])) {

			require_once ($fs_options[$fs_action]["action"]);
			exit (1);

		} elseif (isset ($fs_options[$fs_action]["redirect"])) {

			header ("Location: {$fs_options[$fs_action]["redirect"]}");
			exit (1);
		}
	} else if ($fs_action == "cancel") {

		$fs_action = "view";
		$fieldset->parse ("cancel");
		$fieldset->retrieve ();
		$_REQUEST[$fs_primary_key] =
				$fieldset->get_field ($fieldset->get_option
				("primary_key"))->get_variable ("value");
	} else if ($fs_action == "addnew") {

		$fieldset->parse ("addnew");
		$input = true;
	} else if ($fs_action == "view") {

		$_REQUEST[$fs_action_value] = $fs_action;
		$fieldset->retrieve ();
	}

	if ($fs_trans_commit) {
		if ($success) $_GLOBAL_DBH->query ("COMMIT");
		else $_GLOBAL_DBH->query ("ROLLBACK");
	}

	$_REQUEST[$fs_action_value] = $fs_action;
	
	return (array ($input, $fs_action, $store, $valid, $success));
}



function _app_create_fieldset_object ($options) {

	$db_conn = $options["db_conn"];
	$fieldset = $options["fieldset"];
	$fieldset_id = $options["fieldset_id"];
	$fs_action = $options["fs_action"];
	$fs_action_field = $options["fs_action_field"];
	$fs_prefix = $options["fs_prefix"];
	$fs_enctype = $options["fs_enctype"];
	$fs_link = $options["fs_link"];
	$fs_options = $options["fs_options"];
	$fs_actions = $options["fs_actions"];
	$fs_input = $options["fs_input"];
	$fs_title = $options["fs_title"];

	$_OBJECT_FS_CONTROL = new Container ();
	$_OBJECT_FS_CONTROL->set_callback_begin
			("_template_fieldset_begin");
	$_OBJECT_FS_CONTROL->set_callback_end
			("_template_fieldset_end");
	$_OBJECT_FS_CONTROL->set_variable ("fieldset", $fieldset);
	$_OBJECT_FS_CONTROL->set_variable ("action_field", ($fs_action_field
			? $fs_action_field : "fs_action"));
	$_OBJECT_FS_CONTROL->set_variable ("action", $fs_link);
	$_OBJECT_FS_CONTROL->set_variable ("enctype", $fs_enctype);
	#$_OBJECT_FS_CONTROL->set_variable ("name", $fieldset_id);
	$_OBJECT_FS_CONTROL->set_variable ("fieldset_id", $fieldset_id);
	$_OBJECT_FS_CONTROL->set_variable ("fs_title", $fs_title);

	if (is_array ($fieldset)) {

		foreach ($fieldset as $set)

			_app_parse_fieldset ($options,
					$_OBJECT_FS_CONTROL, $set);
	} else _app_parse_fieldset ($options, $_OBJECT_FS_CONTROL, $fieldset);

	if ($fs_options) {

		$_OBJECT_FIELD_ENTRY = new Container ();
		$_OBJECT_FIELD_ENTRY->set_callback_begin
				("_template_fieldset_options_begin");
		$_OBJECT_FIELD_ENTRY->set_callback_end
				("_template_fieldset_options_end");
		$_OBJECT_FIELD_ENTRY->set_variable ("fieldset", $fieldset);
		
		if ($fs_action == "view") {

			if ($fs_options["close"])
				$_OBJECT_FIELD_ENTRY->insert_container
				(_app_create_option ("close", $options));
			if ($fs_options["modify"])
				$_OBJECT_FIELD_ENTRY->insert_container
				(_app_create_option ("modify", $options));
			if ($fs_options["remove"])
				$_OBJECT_FIELD_ENTRY->insert_container
				(_app_create_option ("remove", $options));
		} elseif ($fs_action == "modify") {

			if ($fs_options["cancel"])
				$_OBJECT_FIELD_ENTRY->insert_container
				(_app_create_option ("cancel", $options));
			if ($fs_options["update"])
				$_OBJECT_FIELD_ENTRY->insert_container
				(_app_create_option ("update", $options));
		} elseif ($fs_action == "remove") {

			if ($fs_options["cancel"])
				$_OBJECT_FIELD_ENTRY->insert_container
				(_app_create_option ("cancel", $options));
			if ($fs_options["delete"])
				$_OBJECT_FIELD_ENTRY->insert_container
				(_app_create_option ("delete", $options));
		} elseif ($fs_action == "addnew") {

			if ($fs_options["canret"])
				$_OBJECT_FIELD_ENTRY->insert_container
				(_app_create_option ("canret", $options));
			if ($fs_options["create"])
				$_OBJECT_FIELD_ENTRY->insert_container
				(_app_create_option ("create", $options));
		}

		$_OBJECT_FS_CONTROL->insert_container ($_OBJECT_FIELD_ENTRY);
	}

	if ($fs_actions) {

		$_OBJECT_FIELD_ENTRY = new Container ();
		$_OBJECT_FIELD_ENTRY->set_callback_begin
				("_template_fieldset_options_begin");
		$_OBJECT_FIELD_ENTRY->set_callback_end
				("_template_fieldset_options_end");
		$_OBJECT_FIELD_ENTRY->set_variable ("fieldset", $fieldset);

		foreach ($fs_actions as $option) {
		
			$_OBJECT_FIELD_ENTRY->insert_container
				(_app_create_action ($option, $options));
		}

		$_OBJECT_FS_CONTROL->insert_container ($_OBJECT_FIELD_ENTRY);
	}

	return $_OBJECT_FS_CONTROL;
}

function _app_parse_fieldset ($options, $_OBJECT_FS_CONTROL, $fieldset) {

	$db_conn = $options["db_conn"];
	$fieldset_id = $options["fieldset_id"];
	$fs_action = $options["fs_action"];
	$fs_prefix = $options["fs_prefix"];
	$fs_link = $options["fs_link"];
	$fs_options = $options["fs_options"];
	$fs_input = $options["fs_input"];

	while ($field = $fieldset->next_field ()) {

		if (!$fs_input && $field->get_variable ("internal") &&
				!$field->get_variable ("multiple_relation"))

			continue;
		
		if ($field->get_variable("rkey")) continue;
		if ($field->get_variable("no_access_flag")) continue;
		
		$_OBJECT_FIELD_ENTRY = new Container ();

		if (preg_match ("/hidden/", $field->get_variable ("input"))
				|| $field->get_option ("primary_key")) {

			$_OBJECT_FIELD_ENTRY->set_callback_begin
					("_template_fieldset_hidden");
			$_OBJECT_FIELD_ENTRY->set_option
					("callback_end", false);
			$_OBJECT_FIELD_ENTRY->set_variable ("name", $fs_prefix .
					$field->get_variable ("name"));
			$_OBJECT_FIELD_ENTRY->set_variable ("value",
					$field->get_variable ("value"));
			$_OBJECT_FIELD_ENTRY->set_variable
					("fieldset", $fieldset);
			$_OBJECT_FIELD_ENTRY->set_variable
					("field", $field);
		} else {

			$_OBJECT_FIELD_ENTRY->set_callback_begin
					("_template_fieldset_entry_begin");
			$_OBJECT_FIELD_ENTRY->set_callback_end
					("_template_fieldset_entry_end");
			$_OBJECT_FIELD_ENTRY->set_variable
					("fieldset", $fieldset);
			$_OBJECT_FIELD_ENTRY->set_variable
					("field", $field);
			$_OBJECT_FIELD_ENTRY->set_variable
					("db_conn", $db_conn);

			$_OBJECT_FIELD_LABEL = new Container ();
			$_OBJECT_FIELD_LABEL->set_callback_begin
					("_template_fieldset_label");
			$_OBJECT_FIELD_LABEL->set_option
					("callback_end", false);
			$_OBJECT_FIELD_LABEL->set_variable ("label",
					$field->get_variable ("label"));
			$_OBJECT_FIELD_LABEL->set_variable ("comment",
					$field->get_variable ("comment"));
			$_OBJECT_FIELD_LABEL->set_variable
					("fieldset", $fieldset);
			$_OBJECT_FIELD_LABEL->set_variable
					("field", $field);

			$_OBJECT_FIELD_VALUE = new Container ();
			$_OBJECT_FIELD_VALUE->set_callback_begin ($fs_input ?
					"_template_fieldset_input" :
					"_template_fieldset_value");
			$_OBJECT_FIELD_VALUE->set_option
					("callback_end", false);
			$_OBJECT_FIELD_VALUE->set_variable ("name", $fs_prefix .
					$name=$field->get_variable ("name"));
			$_OBJECT_FIELD_VALUE->set_variable ("value",
					$field->get_variable ("value"));
			$_OBJECT_FIELD_VALUE->set_variable ("input",
					$field->get_variable ("input"));
			$_OBJECT_FIELD_VALUE->set_variable ("style",
					$style=$field->get_variable ("style"));

			foreach (array ("title","date_begin","notes") as $key) {
				if (!$style && $name == $key)
					$_OBJECT_FIELD_VALUE->set_variable
					("style", "css_fieldset_value_bold");
			}

			$_OBJECT_FIELD_VALUE->set_variable
					("fieldset", $fieldset);
			$_OBJECT_FIELD_VALUE->set_variable
					("field", $field);

			$_OBJECT_FIELD_ENTRY->insert_container
					($_OBJECT_FIELD_LABEL);
			$_OBJECT_FIELD_ENTRY->insert_container
					($_OBJECT_FIELD_VALUE);
		}

		$_OBJECT_FS_CONTROL->insert_container ($_OBJECT_FIELD_ENTRY);
	}
}

function _app_create_action ($option, $options) {

	$fieldset = $options["fieldset"];
	$fieldset_id = $options["fieldset_id"];
	$fs_action = $options["fs_action"];
	$fs_action_field = $options["fs_action_field"] ?
			$options["fs_action_field"] : "fs_action";
	$fs_link = $options["fs_link"];
	$fs_options = $options["fs_options"];
	
	if (is_array ($fieldset)) $fieldset = $fieldset[0];

	$_OBJECT_FS_ACTION = new Container ();
	$_OBJECT_FS_ACTION->set_callback_begin ("_template_fieldset_option");
	$_OBJECT_FS_ACTION->set_option ("callback_end", false);
	$_OBJECT_FS_ACTION->set_variable ("fieldset_id", $fieldset_id);
	$_OBJECT_FS_ACTION->set_variable ("option", $option);
	$_OBJECT_FS_ACTION->set_variable ("action_field", $fs_action_field);
	$_OBJECT_FS_ACTION->set_variable ("action",
			$option["action"] ? $option["action"] : $fs_link);
	$_OBJECT_FS_ACTION->set_variable ("label",
			$option["label"]);

	return $_OBJECT_FS_ACTION;
}

function _app_create_option ($option, $options) {

	$fieldset = $options["fieldset"];
	$fieldset_id = $options["fieldset_id"];
	$fs_action = $options["fs_action"];
	$fs_action_field = $options["fs_action_field"] ?
			$options["fs_action_field"] : "fs_action";
	$fs_link = $options["fs_link"];
	$fs_options = $options["fs_options"];
	$fs_access = isset ($options["fs_access"]) ? $options["fs_access"] : array ();
	$fs_access["data"] = isset ($fs_access["data"]) ? $fs_access["data"] : array ();
	
	if (is_array ($fieldset)) $fieldset = $fieldset[0];

	foreach ($fs_access["data"] as $key => $val) {
				
		if (preg_grep ("/^{$option}$/", $val)) {
					
			$data = $key;
			reset ($fs_access["data"]);
			break;
		}       
					
	}

	$module = isset ($fs_options[$option]["access"]["module"]) ?
			$fs_options[$option]["access"]["module"] :
			$fieldset->get_access ("module");
	$right = isset ($fs_options[$option]["access"]["right"]) ?
			$fs_options[$option]["access"]["right"] :
			$fieldset->get_access ("right");
	if (!$data) $data = isset ($fs_options[$option]["access"]["data"]) ?
			$fs_options[$option]["access"]["data"] :
			isset ($fs_options[$option]["data_access"]) ?
			$fs_options[$option]["data_access"] :
			$fieldset->get_access ("data");

	if (!_app_verify_object_data_right (array (
					module=>$module,
					right=>$right,
					data=>$data
			))) return null;
	
	/* if (($module = ($fs_options[$option]["access"]["module"] ?
				$fs_options[$option]["access"]["module"] :
				$fieldset->get_access ("module"))) &&
			($right = $fs_options[$option]["access"]["right"] ?
				$fs_options[$option]["access"]["right"] :
				$fieldset->get_access ("right")) &&
			($data = $fs_options[$option]["access"]["data"]) &&
			!_app_verify_object_data_right (array (
					module=>$module,
					right=>$right,
					data=>$data
			)))
	
		return null; */
	#print $module.$right.$data."<br>";

	$_OBJECT_FS_OPTION = new Container ();
	$_OBJECT_FS_OPTION->set_callback_begin ("_template_fieldset_option");
	$_OBJECT_FS_OPTION->set_option ("callback_end", false);
	$_OBJECT_FS_OPTION->set_variable ("fieldset_id", $fieldset_id);
	$_OBJECT_FS_OPTION->set_variable ("option", $option);
	$_OBJECT_FS_OPTION->set_variable ("action_field", $fs_action_field);
	$_OBJECT_FS_OPTION->set_variable ("action",
			$fs_options[$option]["action"] ?
			$fs_options[$option]["action"] : $fs_link);
	$_OBJECT_FS_OPTION->set_variable ("label",
			$fs_options[$option]["label"]);

	return $_OBJECT_FS_OPTION;
}

function _app_store_image($image,$path,$name,$options) {

	require_once("bitmap.php");

	if ($_FILES[$image]["name"]) {

		list ($_height, $_width) = split ("x", $options["size"]);

		$filename = $_FILES[$image]["tmp_name"];
		list($width, $height) = getimagesize($filename);

		if ($width > $height) {

			$new_width = round ($width * ($_width / $width));
			$new_height = round ($height * ($_width / $width));
		} else {

			$new_height = round ($height * ($_height / $height));
			$new_width = round ($width * ($_height / $height));
		}

		$thumb = @imagecreatetruecolor($new_width,$new_height);

		switch(exif_imagetype($_FILES[$image]["tmp_name"])) {

			case IMAGETYPE_GIF:
				$source=@imagecreatefromgif($filename);
				break;
			case IMAGETYPE_JPEG:
				$source=@imagecreatefromjpeg($filename);
				break;
			case IMAGETYPE_PNG:
				$source=@imagecreatefrompng($filename);
				break;
			case IMAGETYPE_BMP:
				$source=@ImageCreateFromBMP($filename);
				break;
			default: break;
		}

		imagecopyresampled($thumb, $source, 0, 0,
				0, 0, $new_width, $new_height, $width, $height);

		if (file_exists ($path.$name)) unlink ($path.$name);

		imagejpeg($thumb,$path.$name,100);
		return 1;
	}
}

function _app_relation_multiple ($fieldset, $field, $input=false, $options=false) {

	if ($input) {

		if (function_exists ($callback = $field->get_variable ("multiple_insert_callback")))
			$callback ($fieldset, $field, $input);
		else _app_insert_multiple ($fieldset, $field, $input);
	} else {

		if (function_exists ($callback = $field->get_variable ("multiple_select_callback")))
			return $callback ($fieldset, $field, $options);
		else return _app_select_multiple ($fieldset, $field, $options);
	}
}

function _app_insert_multiple ($fieldset, $field) {

	$values = $field->get_variable ("value");
	$multiple = $field->get_variable ("multiple_relation");
	$relation = $multiple["relation"];
	$local = $multiple["relation_keys"]["local"];
	$foreign = $multiple["relation_keys"]["foreign"];
	$local_value = $fieldset->get_field ($fieldset->get_option
			("primary_key"))->get_variable ("value");


	$fieldset->get_option ("db_conn")->query ("DELETE FROM {$relation} WHERE {$local}={$local_value}");
	if (isset ($values)) foreach ($values as $foreign_value) {

		#print ("DELETE FROM {$relation} WHERE {$local}={$local_value} AND $foreign=$foreign_value");
		#$fieldset->get_option ("db_conn")->query ("DELETE FROM {$relation} WHERE {$local}={$local_value} AND $foreign=$foreign_value");
		#print ("INSERT INTO {$relation}({$local},{$foreign}) VALUES($local_value,$foreign_value)<br>");
		$fieldset->get_option ("db_conn")->query ("INSERT INTO {$relation}({$local},{$foreign}) VALUES($local_value,$foreign_value)");
	}
}

function _app_select_multiple ($fieldset, $field, $options=false) {

	$variable = $field->get_variable ("multiple_relation");
	$relation = $variable["relation"];
	$local = "{$fieldset->get_option ("relation")}.{$fieldset->get_option ("primary_key")}";
	$local_value = "{$local}={$fieldset->get_field ($fieldset->get_option ("primary_key"))->get_variable ("value")}";

	if ($options) $fields = "{$variable["foreign"]}.{$variable["foreign_columns"]["key"]}";
	else $fields = "{$variable["foreign"]}.{$variable["foreign_columns"]["value"]}";
	
	if ($fieldset->get_option ("relation") == $variable["foreign"]) {
		
		$relations = "{$variable["relation"]},{$variable["foreign"]}";
		$sql_relation =<<<SQL
SELECT {$fields} FROM {$relations} WHERE {$relation}.{$variable["relation_keys"]["local"]}={$fieldset->get_field ($fieldset->get_option ("primary_key"))->get_variable ("value")} AND {$relation}.{$variable["relation_keys"]["foreign"]}={$variable["foreign"]}.{$variable["foreign_columns"]["key"]}
SQL;
	} else {
		
		$relations = "{$variable["relation"]},{$fieldset->get_option ("relation")},{$variable["foreign"]}";
		$sql_relation =<<<SQL
SELECT {$fields} FROM {$relations} WHERE {$local_value} AND {$relation}.{$variable["relation_keys"]["local"]}={$local} AND {$relation}.{$variable["relation_keys"]["foreign"]}={$variable["foreign"]}.{$variable["foreign_columns"]["key"]}
SQL;
	}

	$result = $fieldset->get_option ("db_conn")->query ($sql_relation);
	$_result = array ();

	while ($rows = $fieldset->get_option ("db_conn")->fetch_object ($result)) {

		
		if ($options)  array_push ($_result, $rows->$variable["foreign_columns"]["key"]);
		else array_push ($_result, $rows->$variable["foreign_columns"]["value"]);
	}

	if ($options) return $_result;
	return join ("\n", $_result);
}

?>
